Leetcode102——Binary Tree Level Order Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its level order traversal as:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

2. 求解

这个题就是一个树的层次遍历问题,需要用到新的数据结构队列,把每一层的结点的子结点放入到队列中,依次遍历。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if(root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
Queue<TreeNode> result = new LinkedList<TreeNode>();
List<Integer> level = new ArrayList<Integer>();
while(!queue.isEmpty()) {
TreeNode temp = queue.poll();
level.add(temp.val);
if(temp.left != null) {
result.add(temp.left);
}
if(temp.right != null) {
result.add(temp.right);
}
if(queue.isEmpty()) {
queue = result;
result = new LinkedList<TreeNode>();
list.add(level);
level = new ArrayList<Integer>();
}
}
return list;
}
}
如果有收获,可以请我喝杯咖啡!